package com.recource.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.recource.annonation.Login;
import com.recource.domain.*;

import com.recource.ro.CoachRO;
import com.recource.ro.UserRO;
import com.recource.util.HostHolder;
import com.recource.util.SystemUtil;
import com.recource.vo.PageVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.recource.dao.*;
import com.recource.ro.PageRO;

import net.sf.jsqlparser.Model;
import org.apache.commons.collections4.SetUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.security.MessageDigest;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/admin")
@Transactional(rollbackFor = Exception.class)
@Login
public class AdminController {

    @Autowired
    private UserDao userDao;


    @Autowired
    private UserTypesMapper userTypesMapper;

    @Autowired
    private CoachMapper coachMapper;

    @Autowired
    private VipMapper vipMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private ProductMapper productMapper;



    @Value("${file.root}")
    private String root;

    @Value("${system.previewUrl}")
    private String url;


    @RequestMapping("/index")
    public String index() {
        return "/admin/index";
    }

    @RequestMapping("/user/add.html")
    public String addHtml() {
        return "/admin/user/detail";
    }

    //用户列表分页接口
    @RequestMapping("/user/page")
    public ModelAndView list(PageRO<User> ro) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/user/list");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //查找是否请求参数中有搜索值
        if (StringUtils.isNotEmpty(ro.getSearch())) {
            //模糊查找用户是否符合要求
            wrapper.like(User::getUsername, ro.getSearch());
        }
        //分页查询用户
        PageRO<User> userPageRO = userDao.selectPage(ro, wrapper);
        userPageRO.getRecords().forEach(u -> {
            LambdaQueryWrapper<UserTypes> userTypesLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userTypesLambdaQueryWrapper.eq(UserTypes::getId, u.getUserTypeId());
            UserTypes userTypes = userTypesMapper.selectOne(userTypesLambdaQueryWrapper);
            u.setUserTypes(userTypes);
        });
        //将结果注入页面返回
        modelAndView.addObject("page", userPageRO);
        return modelAndView;
    }


    //用户详情接口
    @RequestMapping("/user/detail")
    public ModelAndView detail(String id) {
        ModelAndView modelAndView = new ModelAndView();
        List<UserTypes> userTypes = userTypesMapper.selectList(null);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //where条件搜索是否有符合条件的id用户
        wrapper.eq(User::getId, id);
        User user = userDao.selectOne(wrapper);
        //如果用户不存在就报错
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        //跳转页面
        modelAndView.setViewName("/admin/user/detail");
        //将用户信息注入视图层
        modelAndView.addObject("user", user);
        modelAndView.addObject("userTypes", userTypes);
        return modelAndView;
    }

    //更新和新增用户层
    @RequestMapping("/user/update")
    public ModelAndView update(CoachRO ro) {
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(ro.getId())) {
            wrapper.eq(User::getId, ro.getId());
            //用户id作为查询条件搜索用户
            User user = userDao.selectOne(wrapper);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }
            //将更新内容更新到新属性
            user.setUsername(ro.getUsername());
//            user.setUserType(ro.getUserType());
            user.setPhone(ro.getPhone());
            user.setAddress(ro.getAddress());
            user.setUserTypeId(ro.getUserTypeId());
            //在数据库中更新用户
            userDao.updateById(user);
        } else {
            //新增用户
            //查看用户名是否存在
            wrapper.eq(User::getUsername, ro.getUsername());
            User user = userDao.selectOne(wrapper);
            if (user != null) {
                throw new RuntimeException("用户名已经存在了");
            }
            //注入用户的相关信息
            User user1 = new User();
            String salt = UUID.randomUUID().toString().substring(0, 5);
            user1.setSalt(salt);
            StringBuilder sb = new StringBuilder();
            try {
                String password = DigestUtils.md5DigestAsHex((sb.append(salt).append(ro.getPassword())).toString().getBytes());
                user1.setPassword(password);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            user1.setPhone(ro.getPhone());
            user1.setUserTypeId(ro.getUserTypeId());
//            user1.setUserType(ro.getUserType());
            user1.setUsername(ro.getUsername());
            //新增用户
            userDao.insert(user1);
        }
        //跳转视图
        modelAndView.setViewName("redirect:/admin/user/page");
        return modelAndView;
    }

    //删除用户
    @RequestMapping("/user/delete")
    public ModelAndView update(int id) {
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //搜索用户id是否符合条件
        wrapper.eq(User::getId, id);
        //查找用户存在
        User user = userDao.selectOne(wrapper);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        if (StringUtils.equals(user.getUsername(), "admin")) {
            throw new RuntimeException("用户不可删除");
        }
        //删除数据库记录
        userDao.deleteById(user);
        //重定向视图
        modelAndView.setViewName("redirect:/admin/user/page");
        return modelAndView;
    }

    //增删查改项目
    @RequestMapping("/project/update")
    public ModelAndView updateProject(Project ro) {
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(ro.getId())) {
            wrapper.eq(Project::getId, ro.getId());
            //用户id作为查询条件搜索用户
            Project project = projectMapper.selectOne(wrapper);
            if (project == null) {
                throw new RuntimeException("项目不存在");
            }
            //将更新内容更新到新属性
            projectMapper.updateById(ro);
        } else {
            //新增用户
            //查看用户名是否存在
            wrapper.eq(Project::getName, ro.getName());
            Project project = projectMapper.selectOne(wrapper);
            if (project != null) {
                throw new RuntimeException("项目已经存在了");
            }
           projectMapper.insert(ro);
        }
        //跳转视图
        modelAndView.setViewName("redirect:/admin/project/page");
        return modelAndView;
    }

    @RequestMapping("/project/page")
    public ModelAndView listProject(PageRO<Project> ro) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/project/list");
        LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
        //查找是否请求参数中有搜索值
        if (StringUtils.isNotEmpty(ro.getSearch())) {
            //模糊查找用户是否符合要求
            wrapper.like(Project::getName, ro.getSearch());
        }
        PageRO<Project> projectPageRO = projectMapper.selectPage(ro, wrapper);
        modelAndView.addObject("page", projectPageRO);
        return modelAndView;
    }


    @RequestMapping("/project/delete")
    public ModelAndView project(int id) {
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
        //搜索用户id是否符合条件
        wrapper.eq(Project::getId, id);
        //查找用户存在
        //User user = userDao.selectOne(wrapper);

        //Coach coach = coachMapper.selectOne(wrapper);

        Project project = projectMapper.selectOne(wrapper);

        if (project == null) {
            throw new RuntimeException("用户不存在");
        }

        //删除数据库记录
        projectMapper.deleteById(project);
        //重定向视图
        modelAndView.setViewName("redirect:/admin/project/page");
        return modelAndView;
    }


    //增删查改教练
    @RequestMapping("/coach/update")
    public ModelAndView updateCoach(CoachRO ro) {
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(ro.getId())) {
            wrapper.eq(User::getId, ro.getId());
            //用户id作为查询条件搜索用户
            User user = userDao.selectOne(wrapper);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }
            //将更新内容更新到新属性
            user.setUsername(ro.getUsername());
//            user.setUserType(ro.getUserType());
            user.setPhone(ro.getPhone());
            user.setAddress(ro.getAddress());
            user.setUserTypeId(ro.getUserTypeId());
            //在数据库中更新用户
            userDao.updateById(user);
            Coach coach = new Coach();
            coach.setName(ro.getName());
            coach.setUserId(user.getId());

            coachMapper.insert(coach);
        } else {
            //新增用户
            //查看用户名是否存在
            wrapper.eq(User::getUsername, ro.getUsername());
            User user = userDao.selectOne(wrapper);
            if (user != null) {
                throw new RuntimeException("用户名已经存在了");
            }
            //注入用户的相关信息
            User user1 = new User();
            String salt = UUID.randomUUID().toString().substring(0, 5);
            user1.setSalt(salt);
            StringBuilder sb = new StringBuilder();
            try {
                String password = DigestUtils.md5DigestAsHex((sb.append(salt).append(ro.getPassword())).toString().getBytes());
                user1.setPassword(password);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            user1.setPhone(ro.getPhone());
            user1.setUserTypeId(ro.getUserTypeId());
//            user1.setUserType(ro.getUserType());
            user1.setUsername(ro.getUsername());
            //新增用户
            userDao.insert(user1);

            Coach coach = new Coach();
            coach.setName(ro.getName());
            coach.setUserId(user1.getId());
            coachMapper.insert(coach);
        }
        //跳转视图
        modelAndView.setViewName("redirect:/admin/coach/page");
        return modelAndView;
    }

    @RequestMapping("/coach/page")
    public ModelAndView listCoach(PageRO<Coach> ro) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/coach/list");
        LambdaQueryWrapper<Coach> wrapper = new LambdaQueryWrapper<>();
        //查找是否请求参数中有搜索值
        if (StringUtils.isNotEmpty(ro.getSearch())) {
            //模糊查找用户是否符合要求
            wrapper.like(Coach::getName, ro.getSearch());
        }
        PageRO<Coach> page = coachMapper.selectPage(ro, wrapper);
        modelAndView.addObject("page", page);
        return modelAndView;
    }


    @RequestMapping("/coach/delete")
    public ModelAndView coach(int id) {
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<Coach> wrapper = new LambdaQueryWrapper<>();
        //搜索用户id是否符合条件
        wrapper.eq(Coach::getId, id);
        //查找用户存在
        //User user = userDao.selectOne(wrapper);

        Coach coach = coachMapper.selectOne(wrapper);

        if (coach == null) {
            throw new RuntimeException("用户不存在");
        }

        //删除数据库记录
        coachMapper.deleteById(coach);
        //重定向视图
        modelAndView.setViewName("redirect:/admin/coach/page");
        return modelAndView;
    }

    //TODO

    //增删查改会员
    @RequestMapping("/vip/update")
    public ModelAndView updateVip(Vip ro) {
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<Vip> wrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(ro.getId())) {
            wrapper.eq(Vip::getId, ro.getId());
            //用户id作为查询条件搜索用户
            Vip vip = vipMapper.selectOne(wrapper);
            if (vip == null) {
                throw new RuntimeException("项目不存在");
            }
            //将更新内容更新到新属性
            vipMapper.updateById(ro);
        } else {
            //新增用户
            //查看用户名是否存在
            wrapper.eq(Vip::getName, ro.getName());
            Vip vip = vipMapper.selectOne(wrapper);
            if (vip != null) {
                throw new RuntimeException("项目已经存在了");
            }
            vipMapper.insert(ro);
        }
        //跳转视图
        modelAndView.setViewName("redirect:/admin/vip/page");
        return modelAndView;
    }

    @RequestMapping("/vip/page")
    public ModelAndView listVip(PageRO<Vip> ro) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/vip/list");
        LambdaQueryWrapper<Vip> wrapper = new LambdaQueryWrapper<>();
        //查找是否请求参数中有搜索值
        if (StringUtils.isNotEmpty(ro.getSearch())) {
            //模糊查找用户是否符合要求
            wrapper.like(Vip::getName, ro.getSearch());
        }
        PageRO<Vip> vipPageRO = vipMapper.selectPage(ro, wrapper);
        modelAndView.addObject("page", vipPageRO);
        return modelAndView;
    }


    @RequestMapping("/vip/delete")
    public ModelAndView vip(int id) {
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<Vip> wrapper = new LambdaQueryWrapper<>();
        //搜索用户id是否符合条件
        wrapper.eq(Vip::getId, id);
        //查找用户存在
        //User user = userDao.selectOne(wrapper);

        //Coach coach = coachMapper.selectOne(wrapper);

       // Project project = projectMapper.selectOne(wrapper);
        Vip vip = vipMapper.selectOne(wrapper);

        if (vip == null) {
            throw new RuntimeException("商品不存在");
        }

        //删除数据库记录
        vipMapper.deleteById(vip);
        //重定向视图
        modelAndView.setViewName("redirect:/admin/vip/page");
        return modelAndView;
    }


    //增删查改商品
    @RequestMapping("/product/update")
    public ModelAndView updateProduct(Product ro) {
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(ro.getId())) {
            wrapper.eq(Product::getId, ro.getId());
            //用户id作为查询条件搜索用户
            Product product = productMapper.selectOne(wrapper);
            if (product == null) {
                throw new RuntimeException("项目不存在");
            }
            //将更新内容更新到新属性
            productMapper.updateById(ro);
        } else {
            //新增用户
            //查看用户名是否存在
            wrapper.eq(Product::getName, ro.getName());
            Product product = productMapper.selectOne(wrapper);
            if (product != null) {
                throw new RuntimeException("项目已经存在了");
            }
            productMapper.insert(ro);
        }
        //跳转视图
        modelAndView.setViewName("redirect:/admin/product/page");
        return modelAndView;
    }

    @RequestMapping("/product/page")
    public ModelAndView listProduct(PageRO<Product> ro) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/admin/product/list");
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        //查找是否请求参数中有搜索值
        if (StringUtils.isNotEmpty(ro.getSearch())) {
            //模糊查找用户是否符合要求
            wrapper.like(Product::getName, ro.getSearch());
        }
        PageRO<Product> productPageRO = productMapper.selectPage(ro, wrapper);
        modelAndView.addObject("page", productPageRO);
        return modelAndView;
    }


    @RequestMapping("/product/delete")
    public ModelAndView product(int id) {
        ModelAndView modelAndView = new ModelAndView();
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        //搜索用户id是否符合条件
        wrapper.eq(Product::getId, id);
        //查找用户存在
        //User user = userDao.selectOne(wrapper);

        //Coach coach = coachMapper.selectOne(wrapper);

        // Project project = projectMapper.selectOne(wrapper);
        Product product = productMapper.selectOne(wrapper);

        if (product == null) {
            throw new RuntimeException("商品不存在");
        }

        //删除数据库记录
        productMapper.deleteById(product);
        //重定向视图
        modelAndView.setViewName("redirect:/admin/product/page");
        return modelAndView;
    }

















}